<template>
  <div class="sales-statistics">
    <div class="page-header">
      <h2>销售统计分析</h2>
      <el-date-picker
        v-model="selectedDate"
        type="date"
        placeholder="选择日期"
        value-format="yyyy-MM-dd"
        @change="onDateChange"
        style="margin-left: 20px;"
      />
    </div>

    <!-- 概览卡片 -->
    <el-row :gutter="20" class="overview-section">
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="card-content">
            <div class="card-icon daily">
              <i class="el-icon-s-data"></i>
            </div>
            <div class="card-info">
              <h3>今日销售额</h3>
              <p class="amount">¥{{ dailyStats.total_amount | currency }}</p>
              <span class="count">{{ dailyStats.total_orders }}笔订单</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="card-content">
            <div class="card-icon weekly">
              <i class="el-icon-date"></i>
            </div>
            <div class="card-info">
              <h3>本周销售额</h3>
              <p class="amount">¥{{ weeklyStats.total_amount | currency }}</p>
              <span class="count">{{ weeklyStats.total_orders }}笔订单</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="card-content">
            <div class="card-icon monthly">
              <i class="el-icon-s-marketing"></i>
            </div>
            <div class="card-info">
              <h3>本月销售额</h3>
              <p class="amount">¥{{ monthlyStats.total_amount | currency }}</p>
              <span class="count">{{ monthlyStats.total_orders }}笔订单</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card">
          <div class="card-content">
            <div class="card-icon products">
              <i class="el-icon-goods"></i>
            </div>
            <div class="card-info">
              <h3>商品种类</h3>
              <p class="amount">{{ comprehensiveStats.total_products || 0 }}</p>
              <span class="count">总商品数</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 销售趋势图 -->
      <el-col :span="16">
        <el-card shadow="hover">
          <div slot="header" class="chart-header">
            <span>销售趋势</span>
            <el-radio-group v-model="trendPeriod" size="small" @change="onTrendPeriodChange">
              <el-radio-button label="week">近7天</el-radio-button>
              <el-radio-button label="month">近30天</el-radio-button>
              <el-radio-button label="quarter">近3个月</el-radio-button>
            </el-radio-group>
          </div>
          <v-chart 
            :options="salesTrendOptions" 
            :loading="trendLoading"
            style="height: 400px;"
          />
        </el-card>
      </el-col>

      <!-- 热销商品排行 -->
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header" class="chart-header">
            <span>热销商品排行</span>
            <el-select v-model="productPeriod" size="small" @change="onProductPeriodChange">
              <el-option label="今日" value="today"></el-option>
              <el-option label="本周" value="week"></el-option>
              <el-option label="本月" value="month"></el-option>
              <el-option label="本季度" value="quarter"></el-option>
            </el-select>
          </div>
          <v-chart 
            :options="topProductsOptions" 
            :loading="productsLoading"
            style="height: 400px;"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-row :gutter="20" class="table-section">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header">
            <span>热销商品详情</span>
            <el-button 
              style="float: right; padding: 3px 0" 
              type="text" 
              @click="exportData"
            >
              导出数据
            </el-button>
          </div>
          <el-table 
            :data="topProductsList" 
            :loading="productsLoading"
            stripe
            style="width: 100%"
          >
            <el-table-column prop="rank" label="排名" width="80" align="center">
              <template slot-scope="scope">
                <el-tag 
                  :type="scope.row.rank <= 3 ? 'danger' : scope.row.rank <= 10 ? 'warning' : 'info'"
                  size="small"
                >
                  {{ scope.row.rank }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="product_name" label="商品名称" min-width="200"/>
            <el-table-column prop="sales_quantity" label="销售数量" width="120" align="right">
              <template slot-scope="scope">
                {{ scope.row.sales_quantity | numberFormat }}
              </template>
            </el-table-column>
            <el-table-column prop="sales_amount" label="销售金额" width="150" align="right">
              <template slot-scope="scope">
                ¥{{ scope.row.sales_amount | currency }}
              </template>
            </el-table-column>
            <el-table-column prop="percentage" label="占比" width="100" align="right">
              <template slot-scope="scope">
                {{ (scope.row.percentage * 100).toFixed(2) }}%
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getDailySales,
  getWeeklySales,
  getMonthlySales,
  getTopProducts,
  getSalesCurve,
  getComprehensiveStats
} from '@/api/statistics'

export default {
  name: 'SalesStatistics',
  filters: {
    currency(value) {
      if (!value) return '0.00'
      return parseFloat(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },
    numberFormat(value) {
      if (!value) return '0'
      return parseInt(value).toLocaleString('zh-CN')
    }
  },
  data() {
    return {
      selectedDate: new Date().toISOString().split('T')[0],
      trendPeriod: 'month',
      productPeriod: 'month',
      
      // 数据
      dailyStats: {},
      weeklyStats: {},
      monthlyStats: {},
      comprehensiveStats: {},
      salesCurveData: [],
      topProductsList: [],
      
      // 加载状态
      trendLoading: false,
      productsLoading: false
    }
  },
  computed: {
    // 销售趋势图配置
    salesTrendOptions() {
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['销售额', '订单数']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.salesCurveData.map(item => item.date || item.period)
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            position: 'left',
            axisLabel: {
              formatter: '¥{value}'
            }
          },
          {
            type: 'value',
            name: '订单数',
            position: 'right',
            axisLabel: {
              formatter: '{value}笔'
            }
          }
        ],
        series: [
          {
            name: '销售额',
            type: 'line',
            data: this.salesCurveData.map(item => item.total_amount || 0),
            smooth: true,
            yAxisIndex: 0,
            lineStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(64, 158, 255, 0.8)'
                }, {
                  offset: 1, color: 'rgba(64, 158, 255, 0.1)'
                }]
              }
            }
          },
          {
            name: '订单数',
            type: 'line',
            data: this.salesCurveData.map(item => item.total_orders || 0),
            smooth: true,
            yAxisIndex: 1,
            lineStyle: {
              color: '#67C23A'
            }
          }
        ]
      }
    },
    
    // 热销商品图配置
    topProductsOptions() {
      const data = this.topProductsList.slice(0, 10).map((item, index) => ({
        value: item.sales_quantity || 0,
        name: item.product_name || `商品${index + 1}`
      }))
      
      return {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: data.map(item => item.name)
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: false,
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '12'
              }
            },
            data: data
          }
        ]
      }
    }
  },
  created() {
    this.fetchAllData()
  },
  methods: {
    async fetchAllData() {
      await Promise.all([
        this.fetchDailyStats(),
        this.fetchWeeklyStats(),
        this.fetchMonthlyStats(),
        this.fetchComprehensiveStats(),
        this.fetchSalesCurve(),
        this.fetchTopProducts()
      ])
    },
    
    async fetchDailyStats() {
      try {
        const response = await getDailySales(this.selectedDate)
        this.dailyStats = response.data || {}
      } catch (error) {
        console.error('获取日销售统计失败：', error)
        this.$message.error('获取日销售统计失败')
      }
    },
    
    async fetchWeeklyStats() {
      try {
        const response = await getWeeklySales()
        this.weeklyStats = response.data || {}
      } catch (error) {
        console.error('获取周销售统计失败：', error)
        this.$message.error('获取周销售统计失败')
      }
    },
    
    async fetchMonthlyStats() {
      try {
        const response = await getMonthlySales()
        this.monthlyStats = response.data || {}
      } catch (error) {
        console.error('获取月销售统计失败：', error)
        this.$message.error('获取月销售统计失败')
      }
    },
    
    async fetchComprehensiveStats() {
      try {
        const response = await getComprehensiveStats()
        this.comprehensiveStats = response.data || {}
      } catch (error) {
        console.error('获取综合统计失败：', error)
        this.$message.error('获取综合统计失败')
      }
    },
    
    async fetchSalesCurve() {
      this.trendLoading = true
      try {
        const response = await getSalesCurve(this.trendPeriod, 'day')
        this.salesCurveData = response.data || []
      } catch (error) {
        console.error('获取销售曲线失败：', error)
        this.$message.error('获取销售曲线失败')
      } finally {
        this.trendLoading = false
      }
    },
    
    async fetchTopProducts() {
      this.productsLoading = true
      try {
        const response = await getTopProducts(this.productPeriod, 20)
        this.topProductsList = (response.data || []).map((item, index) => ({
          ...item,
          rank: index + 1
        }))
      } catch (error) {
        console.error('获取热销商品失败：', error)
        this.$message.error('获取热销商品失败')
      } finally {
        this.productsLoading = false
      }
    },
    
    onDateChange() {
      this.fetchDailyStats()
    },
    
    onTrendPeriodChange() {
      this.fetchSalesCurve()
    },
    
    onProductPeriodChange() {
      this.fetchTopProducts()
    },
    
    exportData() {
      // 导出数据功能
      const csvContent = this.generateCSV()
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `热销商品排行_${new Date().toISOString().split('T')[0]}.csv`
      link.click()
    },
    
    generateCSV() {
      const headers = ['排名', '商品名称', '销售数量', '销售金额', '占比']
      const rows = this.topProductsList.map(item => [
        item.rank,
        item.product_name,
        item.sales_quantity,
        item.sales_amount,
        `${(item.percentage * 100).toFixed(2)}%`
      ])
      
      return [headers, ...rows].map(row => row.join(',')).join('\n')
    }
  }
}
</script>

<style lang="scss" scoped>
.sales-statistics {
  padding: 20px;
  
  .page-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
    }
  }
  
  .overview-section {
    margin-bottom: 20px;
    
    .overview-card {
      .card-content {
        display: flex;
        align-items: center;
        
        .card-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          
          i {
            font-size: 24px;
            color: white;
          }
          
          &.daily {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.weekly {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.monthly {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }
          
          &.products {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
        }
        
        .card-info {
          flex: 1;
          
          h3 {
            margin: 0 0 8px 0;
            font-size: 14px;
            color: #909399;
            font-weight: normal;
          }
          
          .amount {
            margin: 0 0 5px 0;
            font-size: 12px;
            font-weight: bold;
            color: #303133;
          }
          
          .count {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .charts-section {
    margin-bottom: 20px;
    
    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      span {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }
  }
  
  .table-section {
    .el-table {
      .el-tag {
        font-weight: bold;
      }
    }
  }
}
</style> 